﻿using UnityEngine;
using System.Collections;

/// <summary>
/// 实现屏幕截图效果
/// </summary>
public class ScreenShotSctipt : MonoBehaviour
{

    private GameObject clone;
    private LineRenderer line;
    int i;
    //带有LineRender物体
    public GameObject target;

    private Vector3 _startPos;
    private Vector3 _endPos;

    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //实例化对象
            clone = (GameObject)Instantiate(target, target.transform.position, Quaternion.identity);

            //获得该物体上的LineRender组件
            line = clone.GetComponent<LineRenderer>();
            //设置起始和结束的颜色
            line.startColor = Color.red;
            line.endColor = Color.red;

            //设置起始和结束的宽度
            //line.SetWidth(0.2f, 0.1f);
            line.startWidth = 0.02f;
            line.endWidth = 0.02f;

            //计数
            i = 0;


            _startPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 15));

        }
        if (Input.GetMouseButton(0))
        {
            ////每一帧检测，按下鼠标的时间越长，计数越多
            //i++;
            ////设置顶点数
            ////line.SetVertexCount(i);
            //line.positionCount = i;
            ////设置顶点位置(顶点的索引，将鼠标点击的屏幕坐标转换为世界坐标)
            //line.SetPosition(i - 1, Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 15)));

            DrawRectangle();
        }

    }

    /// <summary>
    /// 画矩形
    /// </summary>
    private void DrawRectangle()
    {
        line.positionCount = 5;
        _endPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 15));

        Vector3[] pos = new Vector3[5];
        pos[0] = _startPos;
        pos[1] = new Vector3(_startPos.x, _endPos.y, _startPos.z);
        pos[2] = _endPos;
        pos[3] = new Vector3(_endPos.x, _startPos.y, _startPos.z);
        pos[4] = _startPos;

        line.SetPositions(pos);

    }



}